<template>
  <div class="position-manage">
    <div class="main">
      <!-- 左侧类型选择 -->
<!--      <div class="type-selector">-->
<!--        <div class="type-title">管理类型</div>-->
<!--        <div -->
<!--          class="type-item" -->
<!--          :class="{ active: currentType === 4 }" -->
<!--          @click="switchType(4)"-->
<!--        >-->
<!--          <i class="el-icon-user"></i>-->
<!--          <span>岗位管理</span>-->
<!--        </div>-->
<!--        <div -->
<!--          class="type-item" -->
<!--          :class="{ active: currentType === 6 }" -->
<!--          @click="switchType(6)"-->
<!--        >-->
<!--          <i class="el-icon-s-tools"></i>-->
<!--          <span>工种管理</span>-->
<!--        </div>-->
<!--      </div>-->

      <!-- 中间树形结构 -->
<!--      <div class="tree-section">-->
<!--        <div class="tree-header">-->
<!--          <span>{{ currentType === 4 ? '岗位' : '工种' }}分类</span>-->
<!--          <el-button type="primary" size="mini" @click="addCategory">-->
<!--            新增一级分类-->
<!--          </el-button>-->
<!--        </div>-->
<!--        <el-tree-->
<!--          ref="tree"-->
<!--          :data="treeData"-->
<!--          :props="{ label: 'label', children: 'children' }"-->
<!--          node-key="id"-->
<!--          default-expand-all-->
<!--          highlight-current-->
<!--          @node-click="handleNodeClick"-->
<!--          class="category-tree"-->
<!--        >-->
<!--          <span class="tree-node" slot-scope="{ node, data }">-->
<!--            <span class="node-label">{{ node.label }}</span>-->
<!--            <span class="node-actions" v-if="data.pid === 0">-->
<!--              <el-button type="text" size="mini" @click.stop="addSubItem(data)">-->
<!--                添加子项-->
<!--              </el-button>-->
<!--              <el-button type="text" size="mini" @click.stop="editCategory(data)">-->
<!--                编辑-->
<!--              </el-button>-->
<!--              <el-button type="text" size="mini" @click.stop="deleteCategory(data)">-->
<!--                删除-->
<!--              </el-button>-->
<!--            </span>-->
<!--          </span>-->
<!--        </el-tree>-->
<!--      </div>-->

      <!-- 右侧内容区域 -->
      <div class="content" >
        <div class="content-header">
          <div class="search-area">
<!--            <div class="input">-->
<!--              <span>名称：</span>-->
<!--              <el-input v-model="queryData.para_name" placeholder="请输入名称" />-->
<!--            </div>-->
<!--            <el-button type="primary" @click="search">查询</el-button>-->
<!--            <el-button @click="reset">重置</el-button>-->
<!--            <el-button type="primary" @click="add">-->
<!--              新增{{ currentType === 4 ? '岗位' : '工种' }}-->
<!--            </el-button>-->
          </div>
        </div>
        <div class="tree-section">
          <div class="tree-header">
            <span>岗位分类</span>
<!--            <el-button @click="reset">重置</el-button>-->
            <el-button type="primary" @click="add" style="margin-right: -180px;">
              新增岗位
            </el-button>
            <el-button type="primary" size="mini" @click="addCategory">
              新增一级岗位
            </el-button>
          </div>
          <el-tree
            ref="tree"
            :data="treeData"
            :props="{ label: 'label', children: 'children' }"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
            class="category-tree"
          >
            <span class="tree-node" slot-scope="{ node, data }">
              <span class="node-label">{{ node.label }}</span>
<!--              <span class="node-actions" v-if="data.pid === 0">-->
              <span class="node-actions" >
                <el-button type="text" size="mini" @click.stop="addSubItem(data)">
                  添加子项
                </el-button>
                <el-button type="text" size="mini" @click.stop="editCategory(data)">
                  编辑
                </el-button>
                <el-button type="text" size="mini" @click.stop="deleteCategory(data)">
                  删除
                </el-button>
              </span>
            </span>
          </el-tree>
        </div>
<!--        <el-table-->
<!--          ref="dataTable"-->
<!--          :data="tableData"-->
<!--          border-->
<!--          v-loading="isTableLoading"-->
<!--          empty-text="暂无数据"-->
<!--          style="width: 100%"-->
<!--          :max-height="tableHeight"-->
<!--        >-->
<!--          <el-table-column type="index" align="center" label="序号" width="60" />-->
<!--          <el-table-column prop="para_name" align="center" label="名称" min-width="200" />-->
<!--          <el-table-column prop="parent_name" align="center" label="上级分类" width="150" />-->
<!--          <el-table-column prop="children_count" align="center" label="子项数量" width="100">-->
<!--            <template #default="scope">-->
<!--              {{ scope.row.children_count || 0 }}-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--          <el-table-column prop="create_time" align="center" label="创建时间" width="180">-->
<!--            <template #default="scope">-->
<!--              {{ formatTime(scope.row.create_time) }}-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--          <el-table-column fixed="right" align="center" label="操作" width="180">-->
<!--            <template #default="scope">-->
<!--              <div class="action">-->
<!--                <span @click="edit(scope.row)">编辑</span>-->
<!--                <span v-if="scope.row.pid === 0" @click="addSubItem(scope.row)">添加子项</span>-->
<!--                <span @click="del(scope.row)">删除</span>-->
<!--              </div>-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--        </el-table>-->

<!--        <el-pagination-->
<!--          background-->
<!--          style="margin-top: 15px; text-align: right"-->
<!--          @size-change="search"-->
<!--          @current-change="getList"-->
<!--          :current-page.sync="queryData.page"-->
<!--          :page-size.sync="queryData.size"-->
<!--          layout="total, prev, pager, next, sizes, jumper"-->
<!--          :total="total"-->
<!--        />-->
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="isShowAdd"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
      >
	  <el-form-item label="上级分类" prop="pid" v-if="!isAddingCategory">
	    <el-select v-model="ruleForm.pid" placeholder="请选择上级分类" style="width: 100%">
	      <el-option label="顶级" :value="0" />
	      <el-option 
	        v-for="item in parentOptions" 
	        :key="item.value" 
	        :label="item.label" 
	        :value="item.value"
	      />
	    </el-select>
	  </el-form-item>
        <el-form-item label="名称" prop="para_name">
          <el-input v-model="ruleForm.para_name" :placeholder="`请输入${currentType === 4 ? '岗位' : '工种'}名称`" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input oninput="value=value.replace(/[^\d.]/g,'')" v-model="ruleForm.sort" placeholder="请输入排序" />
		  <span style="color: red; font-size: 12px;">注:数值越小越靠前</span>
		  
        </el-form-item>
      </el-form>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="subLoading" @click="submitForm">确定</el-button>
      </span>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%" :close-on-click-modal="false">
      <span>确定删除该岗位吗？删除后子项也会被删除。</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="delOk">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { 
  PositionList, 
  PositionSave, 
  PositionInfo, 
  PositionDelete, 
  PositionTree, 
  PositionParentOptions 
} from '@/api/manage';

export default {
  name: 'PositionManage',
  data() {
    return {
      currentType: 4, // 4-岗位，6-工种
      tableHeight: 500,
      isTableLoading: false,
      subLoading: false,
      dialogVisible: false,
      isShowAdd: false,
      isAddingCategory: false, // 是否正在添加一级分类
      tableData: [],
      treeData: [],
      parentOptions: [],
      total: 0,
      queryData: {
        page: 1,
        size: 10,
        para_name: '',
        type: 4,
        pid: null,
        tree_mode: 0
      },
      ruleForm: {
        id: null,
        para_name: '',
        type: 4,
        pid: 0 ,
		sort : '' ,
      },
      rules: {
        para_name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
        ],
		sort: [
		  {  required:true ,message: '请输入排序', trigger: 'blur' },
		]
      },
      deleteItem: null,
      selectedNode: null
    };
  },
  computed: {
    dialogTitle() {
      const typeName = this.currentType === 4 ? '岗位' : '工种';
      const action = this.ruleForm.id ? '编辑' : '新增';
      const level = this.isAddingCategory ? '一级分类' : typeName;
      return `${action}${level}`;
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.tableHeight = window.innerHeight - 350;
    });
    this.initData();
  },
  methods: {
    // 初始化数据
    initData() {
      this.queryData.type = this.currentType;
      this.ruleForm.type = this.currentType;
      this.getTreeData();
      this.getParentOptions();
      this.getList();
    },

    // 切换类型（岗位/工种）
    switchType(type) {
      this.currentType = type;
      this.queryData.type = type;
      this.ruleForm.type = type;
      this.queryData.page = 1;
      this.queryData.pid = null;
      this.selectedNode = null;
      this.initData();
    },

    // 获取树形数据
    getTreeData() {
      PositionTree({ type: this.currentType }).then((res) => {
        this.treeData = res.data || [];
      });
    },

    // 获取父级选项
    getParentOptions() {
      // 使用PositionList接口获取一级分类数据
      PositionList({ 
        type: this.currentType, 
        pid: 0,  // 只获取一级分类
        page: 1,
        size: 100,  // 获取足够多的数据
        tree_mode: 0
      }).then((res) => {
        const list = res.data.list || [];
        // 格式化为下拉框需要的格式
        this.parentOptions = list.map(item => ({
          label: item.para_name,
          value: item.id
        }));
      }).catch((error) => {
        console.error('获取父级选项失败:', error);
        this.parentOptions = [];
      });
    },

    // 获取列表数据
    getList() {
      this.isTableLoading = true;
      PositionList(this.queryData).then((res) => {
        this.isTableLoading = false;
        this.tableData = res.data.list || [];
        this.total = res.data.total || 0;
      }).catch(() => {
        this.isTableLoading = false;
      });
    },

    // 树节点点击
    handleNodeClick(data) {
      this.selectedNode = data;
      this.queryData.pid = data.id;
      this.queryData.page = 1;
      this.getList();
    },

    // 格式化时间
    formatTime(timestamp) {
      if (!timestamp) return '';
      
      let date;
      // 判断是字符串格式还是时间戳格式
      if (typeof timestamp === 'string') {
        // 字符串格式，直接创建Date对象
        date = new Date(timestamp);
      } else {
        // 时间戳格式，需要乘以1000
        date = new Date(timestamp * 1000);
      }
      
      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        return timestamp; // 如果无法解析，返回原始值
      }
      
      return date.toLocaleString('zh-CN');
    },

    // 搜索
    search() {
      this.queryData.page = 1;
      this.getList();
    },

    // 重置
    reset() {
      this.queryData.para_name = '';
      this.queryData.pid = null;
      this.selectedNode = null;
      this.$refs.tree.setCurrentKey(null);
      this.search();
    },

    // 新增一级分类
    addCategory() {
      this.isAddingCategory = true;
      this.ruleForm = {
        id: null,
        para_name: '',
		sort : '' ,
        type: this.currentType,
        pid: 0
      };
      this.isShowAdd = true;
      this.$nextTick(() => {
        this.$refs['ruleForm'].resetFields();
      });
    },

    // 新增子项
    addSubItem(parentData) {
      this.isAddingCategory = false;
      this.ruleForm = {
        id: null,
        para_name: '',
        type: this.currentType,
        pid: parentData.id ,
		sort : '' ,
      };
      this.isShowAdd = true;
      this.$nextTick(() => {
        this.$refs['ruleForm'].resetFields();
      });
    },

    // 新增
    add() {
      this.isAddingCategory = false;
      this.ruleForm = {
        id: null,
        para_name: '',
		sort: '',
        type: this.currentType,
        pid: this.selectedNode ? this.selectedNode.id : 0 ,
		
      };
      this.isShowAdd = true;
      this.$nextTick(() => {
        this.$refs['ruleForm'].resetFields();
      });
    },

    // 编辑分类
    editCategory(data) {
      this.edit(data);
    },

    // 编辑
    edit(item) {
      console.log('编辑项目:', item); // 调试信息
      PositionInfo({ id: item.id }).then((res) => {
        console.log('获取详情成功:', res); // 调试信息
        const data = res.data;
        this.isAddingCategory = data.pid === 0;
        this.ruleForm = {
          id: data.id,
          para_name: data.para_name,
          type: data.type,
          pid: data.pid ,
		  sort : data.sort
        };
        this.isShowAdd = true;
      }).catch((error) => {
        console.error('获取详情失败:', error); // 错误处理
        this.$message.error('获取详情失败，请重试');
      });
    },

    // 删除分类
    deleteCategory(data) {
      this.del(data);
    },

    // 删除
    del(item) {
      this.deleteItem = item;
      this.dialogVisible = true;
    },

    // 确认删除
    delOk() {
      if (this.deleteItem) {
        PositionDelete({ id: this.deleteItem.id }).then((res) => {
          this.$message.success('删除成功');
          this.dialogVisible = false;
          this.deleteItem = null;
          this.getTreeData();
          this.getParentOptions();
          this.getList();
        });
      }
    },

    // 关闭对话框
    handleClose() {
      this.isShowAdd = false;
      this.isAddingCategory = false;
      this.ruleForm = {
        id: null,
        para_name: '',
		  sort: '',
        type: this.currentType,
        pid: 0
      };
    },

    // 提交表单
    submitForm() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.subLoading = true;
          PositionSave(this.ruleForm).then((res) => {
            this.$message.success(this.ruleForm.id ? '修改成功' : '添加成功');
            this.subLoading = false;
            this.isShowAdd = false;
            this.isAddingCategory = false;
            this.getTreeData();
            this.getParentOptions();
            this.getList();
          }).catch(() => {
            this.subLoading = false;
          });
        } else {
          this.$message.error('请正确填写！');
          return false;
        }
      });
    }
  }
};
</script>

<style scoped>
.position-manage {
  width: 100%;
  height: calc(100vh - 100px);
  background: #fff;
  padding: 20px;
  overflow: hidden;
}

.main {
  display: flex;
  height: 100%;
  gap: 20px;
}

/* 左侧类型选择器 */
.type-selector {
  width: 180px;
  flex-shrink: 0;
  border: 1px solid #e3e3e3;
  border-radius: 6px;
  padding: 15px;
}

.type-title {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
}

.type-item {
  display: flex;
  align-items: center;
  padding: 12px 10px;
  margin-bottom: 8px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.type-item:hover {
  background-color: #f5f7fa;
}

.type-item.active {
  background-color: #e6f7ff;
  color: #1890ff;
  border: 1px solid #91d5ff;
}

.type-item i {
  margin-right: 8px;
  font-size: 16px;
}

/* 中间树形结构 */
.tree-section {
  width: 500px;
  flex-shrink: 0;
  border: 1px solid #e3e3e3;
  border-radius: 6px;
  padding: 15px;
}

.tree-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  font-size: 14px;
  font-weight: bold;
}

.category-tree {
  max-height: calc(100vh - 250px);
  overflow-y: auto;
}

.tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.node-label {
  flex: 1;
}

.node-actions {
  display: none;
}

.tree-node:hover .node-actions {
  display: block;
}

.node-actions .el-button {
  padding: 0;
  margin-left: 5px;
}

/* 右侧内容区域 */
.content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding-left: 100px;
}

.content-header {
  margin-bottom: 20px;
}

.search-area {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.input {
  display: flex;
  align-items: center;
}

.input > span {
  font-size: 14px;
  margin-right: 8px;
  flex-shrink: 0;
}

.input .el-input {
  width: 200px;
}

/* 操作按钮 */
.action {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.action span {
  color: #0256ff;
  font-size: 12px;
  cursor: pointer;
}

.action span:hover {
  text-decoration: underline;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .type-selector {
    width: 150px;
  }
  
  .tree-section {
    width: 250px;
  }
}
</style> 